package com.liqi.web.controller.monitor;

import com.alibaba.druid.support.json.JSONUtils;
import com.liqi.common.annotation.Log;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.core.page.TableDataInfo;
import com.liqi.common.enums.BusinessType;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.StringUtils;
import com.liqi.common.utils.poi.ExcelUtil;
import com.liqi.deployment.domain.DvDeployment;
import com.liqi.deployment.domain.DvOperationUser;
import com.liqi.deployment.service.IDvDeploymentService;
import com.liqi.monitor.domain.DvFaultLog;
import com.liqi.monitor.domain.DvWorkOrder;
import com.liqi.monitor.service.IDvFaultLogService;
import com.liqi.monitor.service.IDvWorkOrderService;
import com.liqi.sms.domain.SysShortMessage;
import com.liqi.sms.service.ISysShortMessageService;
import com.liqi.system.domain.SysMail;
import com.liqi.system.service.IDvExceptionInfoService;
import com.liqi.system.service.ISysMailService;
import com.liqi.system.service.device.IDvOperationUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties.Admin;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 故障日志管理Controller
 *
 * @author Lwy
 * @date 2022-02-16
 */
@Api(tags = "异常管理")
@RestController
@RequestMapping("/monitor/faultlog")
public class DvFaultLogController extends BaseController
{


    @Autowired
    private IDvFaultLogService dvFaultLogService;

    @Autowired
    private ISysShortMessageService sysShortMessageService;

    @Autowired
    private ISysMailService SysMailService;
    @Autowired
    private IDvDeploymentService dvDeployDeviceManagerService;
    @Autowired
    private IDvOperationUserService dvOperationUserService;
    @Autowired
    private IDvWorkOrderService dvWorkOrderService;


    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.CarbonCopy}")
    private String CarbonCopy;
    /**
     * 查询故障日志管理列表
     */
    @ApiOperation("异常日志管理查询")
    //@PreAuthorize("@ss.hasPermi('monitor:faultlog:list')")
    @GetMapping("/list")
    public TableDataInfo list(DvFaultLog dvFaultLog)
    {
        startPage();
        List<DvFaultLog> list = dvFaultLogService.selectDvFaultLogList(dvFaultLog);
        return getDataTable(list);
    }

    /**
     * 导出故障日志管理列表
     */
    @ApiOperation("异常日志管理导出")
    //@PreAuthorize("@ss.hasPermi('monitor:faultlog:export')")
    @Log(title = "故障日志管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DvFaultLog dvFaultLog)
    {
        List<DvFaultLog> list = dvFaultLogService.selectDvFaultLogList(dvFaultLog);
        ExcelUtil<DvFaultLog> util = new ExcelUtil<DvFaultLog>(DvFaultLog.class);
        util.exportExcel(response, list, "故障日志管理数据");
    }

    /**
     * 获取故障日志管理详细信息
     */
    @ApiOperation("异常日志管理详细信息")
   // @PreAuthorize("@ss.hasPermi('monitor:faultlog:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dvFaultLogService.selectDvFaultLogById(id));
    }

    /**
     * 新增故障日志管理
     */
    @ApiOperation("异常日志管理新增")
    //@PreAuthorize("@ss.hasPermi('monitor:faultlog:add')")
    @Log(title = "故障日志管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DvFaultLog dvFaultLog)
    {
        dvFaultLog.setCreateUserId(getUserId().toString());
        dvFaultLog.setDeptId(getDeptId().toString());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DvDeployment dvDeployment = dvDeployDeviceManagerService.getByDeviceId(dvFaultLog.getDeviceId());
        if(dvDeployment ==null){
            return AjaxResult.error("设备号异常");
        }
        String deploymentAddress = dvDeployment.getDeploymentAddress();
        DvOperationUser dvOperationUser = dvOperationUserService.selectDvOperationUserByOperationUserName(dvDeployment.getOperationUserName(), dvDeployment.getOperationUserCode());
        if(dvOperationUser==null){
            return AjaxResult.error("运维人员信息有误");
        }

        SysMail sysMail=new SysMail();
        sysMail.setMailFrom(from);
        sysMail.setMailToList(dvOperationUser.getEmail());
        sysMail.setCcList(CarbonCopy);
        sysMail.setSendFlag("0");
        sysMail.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));
        Map<String,Object> map = new HashMap<>();
        map.put("operationUserName", dvDeployment.getOperationUserName());
        map.put("nowTime",df.format(new Date()));
        map.put("deploymentName", dvDeployment.getDeploymentName());
        map.put("deviceId", dvFaultLog.getDeviceId());
        map.put("deploymentAddress", dvDeployment.getAncestorsName()+ dvDeployment.getDeploymentAddress());
        map.put("errorMessage", dvFaultLog.getErrorMessage());

        // 新建短信实体，并插入到短信实体数据库
        SysShortMessage sysShortMessage = new SysShortMessage();
        sysShortMessage.setPhoneNumbers(dvOperationUser.getPhoneNumber());
        sysShortMessage.setCreateTime(DateUtils.getNowDate());
        sysShortMessage.setSendFlag("0");


        sysMail.setSubject("来自"+deploymentAddress+"的设备"+ dvFaultLog.getDeviceId()+"人工上报异常");
        map.put("reportType","人工上报");
        map.put("reportName", dvFaultLog.getReportName());
        map.put("reportPhone", dvFaultLog.getReportPhone());
        String result = JSONUtils.toJSONString(map);
        sysMail.setBody(result);
        sysMail.setCreateBy(dvFaultLog.getReportName());
        sysMail.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));

        sysShortMessage.setTemplateParam(result);
        sysShortMessage.setCreateBy(dvFaultLog.getReportName());
        sysShortMessage.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));

        SysMailService.insertSysMail(sysMail);
        sysShortMessageService.insertSysShortMessage(sysShortMessage);
        //当此异常为人工上报时，调用工单新增方法，自动生成一条工单
        if (StringUtils.isNotBlank(dvFaultLog.getEquipmentFalutType()) && dvFaultLog.getEquipmentFalutType().equals("1")){
            DvWorkOrder dvWorkOrder = new DvWorkOrder();
            dvWorkOrder.setDeviceId(dvFaultLog.getDeviceId());
            dvWorkOrder.setMessage(dvFaultLog.getErrorMessage());
            dvWorkOrder.setReportName(dvFaultLog.getReportName());
            dvWorkOrder.setReportPhone(dvFaultLog.getReportPhone());
            dvWorkOrder.setFaultId(dvFaultLog.getId());
            dvWorkOrder.setOperationUserCode("1");
            dvWorkOrderService.insertDvWorkOrder(dvWorkOrder);
        }
        return toAjax(dvFaultLogService.insertDvFaultLog(dvFaultLog));
    }

    /**
     * 修改故障日志管理
     */
    @ApiOperation("异常日志管理修改")
    //@PreAuthorize("@ss.hasPermi('monitor:faultlog:edit')")
    @Log(title = "故障日志管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DvFaultLog dvFaultLog)
    {
        dvFaultLog.setDeptId(getDeptId().toString());
        return toAjax(dvFaultLogService.updateDvFaultLog(dvFaultLog));
    }

    /**
     * 删除故障日志管理
     */
    @ApiOperation("异常日志管理删除")
    //@PreAuthorize("@ss.hasPermi('monitor:faultlog:remove')")
    @Log(title = "故障日志管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dvFaultLogService.tombstoneFaultLogByIds(ids));
    }
}
